package com.plz.afmt.service.impl;

import com.plz.afmt.service.OssService;
import com.plz.afmt.utils.ConmonUtils;
import com.plz.afmt.utils.NFileUtils;
import com.plz.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 2 * @Author: swing
 * 3 * @Date: 2020/4/1 11:03
 * 4
 */
@Slf4j
@Service
public class DefaultOssServiceImpl extends OssService implements EnvironmentAware, InitializingBean {
    protected Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    protected String ROOT_PATH;

    @Override
    public void afterPropertiesSet() throws Exception {
        String path = environment.getProperty("oss.upload.path");
        if (StringUtils.isNotBlank(path)) {
            ROOT_PATH = path;
        } else {
            //默认路径
            if (ConmonUtils.isLinux()) {
                ROOT_PATH = "/images/";
            } else {
                ROOT_PATH = "C:/images/";
            }
        }
    }

    public String getUploadDir() {
        return ROOT_PATH;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        File outPutFile = createFile(path);
        try {
            FileUtils.copyInputStreamToFile(inputStream, outPutFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("上传文件失败");
        }
        String domain = getDomain();
        if (StringUtils.isNotBlank(domain)) {
            return domain + path;
        } else {
            return path;
        }
    }

    @Override
    public String fbupload(InputStream inputStream, String path) {
        File outPutFile = createFile(path);
        try {
            FileUtils.copyInputStreamToFile(inputStream, outPutFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("上传文件失败");
        }
        String domain = getPath();
        if (StringUtils.isNotBlank(domain)) {
            return domain + path;
        } else {
            return path;
        }
    }

    @Override
    public String quickUploadSuffix(MultipartFile file) throws Exception {
        return quickUploadSuffix(file, NFileUtils.getFileSuffix(file.getOriginalFilename()));
    }

    /**
     * 直接从请求域中将文件上传到服务器本地目录(不采用框架上传方式存放tomcat临时目录，避免两次复制文件)
     *
     * @return
     * @throws Exception
     */
    @Override
    public String quickUploadSuffix(MultipartFile file, String suffix) throws Exception {
        return quickUploadPath(file, getPath(null, suffix));
    }

    @Override
    public String quickUploadPath(MultipartFile file, String path) throws Exception {
        File outPutFile = createFile(path);
        String domain = getDomain() + path;
        file.transferTo(outPutFile);
        return domain;
    }

    @Override
    public String upload(byte[] data, String path) {
        File outPutFile = createFile(path);
        try {
            FileUtils.writeByteArrayToFile(outPutFile, data);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
        String domain = getDomain();
        if (StringUtils.isNotBlank(domain)) {
            return domain + path;
        } else {
            return path;
        }
    }


    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(null, suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(null, suffix));
    }

    @Override
    public Boolean batchUploadFile(String filePath, String directory, String separator) {
        return false;
    }

    private final File createFile(String path) {
        File outPutFile = new File(getUploadDir() + path);
        File fileParentDir = outPutFile.getParentFile();
        if (!fileParentDir.exists()) {
            fileParentDir.mkdirs();
        }
        return outPutFile;
    }

    public final String getDomain() {
        String domain = environment.getProperty("oss.default.domain");
        if (StringUtils.isNotBlank(domain)) {
            if (domain.endsWith("/")) {
                domain = domain.substring(0, domain.length() - 1);
            }
            return domain + getPath();
        }
        return domain;
    }

    public final String getPath() {
        return "/admin/file/view/";
    }

    private final HttpServletRequest getHttpRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private final String getHost() {
        HttpServletRequest request = getHttpRequest();
        String networkProtocol = request.getScheme();
        // 网络ip
        String ip = request.getServerName();
        // 端口号
        Integer port = request.getServerPort();

        String urlPrefix = networkProtocol + "://" + ip;
        if (port != null && port != 80) {
            urlPrefix = urlPrefix + ":" + port;
        }
        return urlPrefix;
    }
}
